﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;

namespace OpenFrameworkCore.Serialize
{
    /// <summary>
    /// OpenFramework에 사용되는 Control을 Serialize, Deserialize하는 클래스
    /// </summary>
    public sealed class Serializer
    {
        /// <summary>
        /// Object를 Serialize하는 메서드
        /// </summary>
        /// <param name="serializedObject">Serialize할 Object</param>
        public string Serialize(Serializable serializedObject)
        {
            try
            {
                // XmlSerializer 생성
                XmlSerializer serializer = new XmlSerializer(serializedObject.GetType());

                using (MemoryStream stream = new MemoryStream())
                {
                    // UTF-8로 Encoding 설정
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Encoding = Encoding.UTF8;

                    using (XmlWriter writer = XmlWriter.Create(stream, settings))
                    {
                        // Serialize 수행
                        serializer.Serialize(writer, serializedObject);

                        stream.Seek(0, SeekOrigin.Begin);

                        // String 값 리턴
                        return new StreamReader(stream).ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SerializeException("Serialize fail", ex);
            }
        }

        /// <summary>
        /// String을 Object로 Deserialize하는 메서드
        /// </summary>
        /// <param name="serializedString">Deserialize할 String</param>
        public Serializable Deserialize(Type type, string serializedString)
        {
            try
            {
                // XmlSerializer 생성
                XmlSerializer serializer = new XmlSerializer(type);

                using (MemoryStream stream = new MemoryStream())
                {
                    // UTF-8로 Encoding 설정
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Encoding = Encoding.UTF8;

                    using (StringReader reader = new StringReader(serializedString))
                        return (Serializable)serializer.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                throw new SerializeException("Deserialize fail", ex);
            }
        }
    }
}
